/**
 * Created Yaro on 2017/8/25.
 */
"use strict";
import React, { Component } from 'react' ;
import { connect } from 'react-redux' ;
import UrlManager from '../../../utils/UrlManager' ;
import NetworkEngine from '../../../utils/NetworkEngine' ;
import { Link, browserHistory } from 'react-router' ;
import { mapStateToProps, mapDispatchToProps } from './MobileMineRedux' ;
import MineFilmsBox from "./MineFims/MineFilmsBox";

//style
import "./MobileMine.scss";

//images
import back from "../../../static/img/h5/return.png";
import tupian from "../../../static/img/h5/1.jpg";
import geren from "../../../static/img/h5/V-geren.png";
import qiye from "../../../static/img/h5/V-qiye.png";
import duihao from "../../../static/img/h5/duihao.png";
import head from "../../../static/img/h5/head.png";
import tx from "../../../static/img/film/moren-tx.png";

class MobileMineContainer extends Component{
    constructor(props){
        super(props) ;
        this.state={
            viewerKey:"",

        }
    }

    componentWillMount() {
        var url = location.href.split('#')[0];
        var arr = url.split("/");
        var creatorId = arr[arr.length-2];
        var viewerKey = arr[arr.length-1];

        var loginUserId = sessionStorage.getItem("id");
        this.state.selfImId = sessionStorage.getItem("imId");
        if(loginUserId != null && loginUserId != ""){
            loginUserId = loginUserId.replace(/\//g, '_');
        }

        this.setState({
            loginUserId: loginUserId,
        })
        this.state.viewerKey = viewerKey;
        // 郭丹 判断用户 2017/11/28 start
        if (creatorId != "" && creatorId != null && creatorId != this.state.loginUserId) {
            this.state.formUserId = creatorId;
        } else {
            this.state.formUserId = this.state.loginUserId;
        }
        this.state.id = creatorId;


        this.initialUser();
        this.initialFilms();
    }

    //退出按钮跳转到广场页
    toExit(){
        sessionStorage.setItem("id","");
        sessionStorage.setItem("selectPage","1")
        sessionStorage.setItem("messageCount","");
        sessionStorage.setItem("displayName", "");
        sessionStorage.setItem("phone", "");
        sessionStorage.setItem("authenticationStatus", "");
        sessionStorage.setItem("headUrl","");
        sessionStorage.clear();
        browserHistory.push("/");
        location.reload();

    }

    //初始化user
    initialUser() {
        let urlManager = new UrlManager();
        NetworkEngine(
            "post",
            urlManager.mobileFindCreator(),
            {
                "creatorId": localStorage.getItem("personalId"),  //creatorId
                "userId": sessionStorage.getItem('id'),
                userKeyId:sessionStorage.getItem("userKeyId"),
                "viewerKey":this.state.viewerKey

            }
        ).then(
            data => {
                let _data = data.data.data;
                console.log("=====个人主页-创作人======", _data.headUrl,_data.userId);
                this.props.initialUser(_data);
            }
        ).catch(
            err => {

            }
        )
    }

    //加关注
    saveFollow(id) {
        let urlManager = new UrlManager();
        NetworkEngine(
            "post",
            urlManager.mobileFollow(),
            {
                "followerId": sessionStorage.getItem("id"),//粉丝 也就是当前用户
                "userId": id,//作者
                "attentionType": "0",
                userKeyId:sessionStorage.getItem("userKeyId")

            }
        ).then(
            data => {
                console.log("data--------------", data.data);
                if (data.data.attentionType === "1") {
                    this.initialUser();
                }
                let tip = $(this.refs.attention);
                tip.show();
                let hide = function () {
                    tip.hide();
                };
                setTimeout(hide, 1500);
            }
        ).catch(
            err => {
                //失败执行
            }
        )
    }

    //取消关注
    unFollow(id) {
        let urlManager = new UrlManager();
        NetworkEngine(
            "post",
            urlManager.mobileUnfollow(),
            {
                "followerId": sessionStorage.getItem("id"),//粉丝 也就是当前用户
                "userId": id,//作者
                "attentionType": "1",
                userKeyId:sessionStorage.getItem("userKeyId")

            }
        ).then(
            data => {
                console.log("data--------------", data.data);
                if (data.data.attentionType === "0") {
                    $(this.refs.cancel_model).show();
                }
            }
        ).catch(
            err => {
                //失败执行
            }
        )
    }

    //点击取消，关闭模态层
    closeModel() {
        $(this.refs.cancel_model).hide();
    }

    //点击确定，关闭模态层，按钮变成"+关注"
    cancelAttention() {
        $(this.refs.cancel_model).hide();
        this.initialUser();
    }

    //返回上一页
    back() {
        history.go(-1);
    }

    //初始化作品列表films
    initialFilms() {
        let urlManager = new UrlManager();
        NetworkEngine(
            // "get",
            // urlManager.mobileFindFilmsByUserId() + `/${localStorage.getItem("personalId")}`,  //creatorId
            "post",
            urlManager.mobileFindFilmsByUserId() ,
            {"creatorId":localStorage.getItem("personalId"),//creatorId
                "userId":sessionStorage.getItem("id"),
                userKeyId:sessionStorage.getItem("userKeyId"),
                "viewerKey":this.state.viewerKey


            }
        ).then(
            data => {
                let _data = data.data;
                console.log("=====个人主页-作品======", _data);
                this.props.initialFilms(_data);
            }
        ).catch(
            err => {

            }
        )
    }

    render(){

        let user = this.props.creator;
        console.log("========创作人信息=========",user);

        //认证图标
        let Logo = () => {
            if(user.status=="1"){
                if (user.authenticationType == "0") {
                    return <img src={geren} alt="图标"/>

                } else {
                    return <img src={qiye} alt="图标"/>

                }
            }else{
                return <div></div>
            }

        };

        let AuthenticationButton = () => {
            //0没登录 2是未关注 3自己 1是已关注
            if (user.isNotFollow == "0") {
                if (sessionStorage.getItem("id") == null) {
                    return <div>
                        <Link to="/Login">
                            <button className="mob-btn">+关注</button>
                        </Link>
                    </div>
                }
            } else if (user.isNotFollow == "2") {
                return <div>
                    <button className="mob-btn" onClick={this.saveFollow.bind(this, user.userId)}>+关注</button>
                </div>
            } else if (user.isNotFollow == "3") {
                return <div></div>
            }
            else {
                return <div>
                    <button className="mob-btn1" onClick={this.unFollow.bind(this, user.userId)}>已关注</button>
                </div>
            }
        };

        let Tab = () => {
            if (localStorage.getItem("personalId") === sessionStorage.getItem('id')) {
                return <div>
                    <p className="li-title">我的作品<span>{user.filmNum ? user.filmNum : 0}</span></p>
                </div>
            } else {
                return <div>
                    <p className="li-title">他的作品<span>{user.filmNum ? user.filmNum : 0}</span></p>
                </div>
            }
        };

        let films = this.props.filmList.data;
        console.log("=====<<<<===作品信息=========",films);
        console.log("========作品数量=========",films.length);
        console.log("===1===",user.id)
        console.log("===2===",sessionStorage.getItem("id"))
        console.log("===3===",sessionStorage.getItem("headUrl"))
        console.log("===4===",user)

        return(



            <div>
                <div>
                    <div className="mine">
                        <div className="back">
                            <img src={back} alt="返回" onClick={this.back.bind(this)}/>
                        </div>
                        <img className="bg" src={user.coverImage} alt="背景"/>
                        <div className="tx">

                            {/*{*/}
                                {/*user.userId==sessionStorage.getItem("id")?<span>*/}
                                      {/*{(sessionStorage.getItem("headUrl")==null||sessionStorage.getItem("headUrl")=="")? <img src={tx} className="tx-img" />:<img src={user.headUrl} className="tx-img"/>*/}
                                      {/*}*/}
                                {/*</span>:<img src={user.headUrl} className="tx-img"/>*/}
                            {/*}*/}

                            <img className="tx-img" src={user.headUrl} alt="头像"/>
                        </div>
                    </div>
                    <div className="m-content clearfix">
                        <div className="m-title clearfix">
                            <p className="p-name fl_l">
                                <span className="fl_l">{user.nickName}</span>
                                <Logo/>
                            </p>
                            <AuthenticationButton/>
                        </div>
                        <div className="m-num clearfix">
                            <p>作品：<span>{user.filmNum ? user.filmNum : 0}</span></p>
                            <p>受喜欢：<span>{user.likeNum ? user.likeNum : 0}</span></p>
                            <p>粉丝：<span>{user.followNum ? user.followNum : 0}</span></p>
                        </div>
                        <div className="m-ms">
                            <p>{user.autograph}</p>
                        </div>
                    </div>
                </div>
                <div className="mine-list">

                    <Tab/>
                    {
                        films.map((data,i)=>{
                            return <MineFilmsBox
                                key={i}
                                filmId={data.filmId}
                                videoLength={data.videoLength}      //视频时长
                                title={data.title}                  //视频标题
                                videoImgUrl={data.videoImgUrl}      //视频封面
                                categoryName={data.categoryName}    //视频类型
                                type={data.type}
                            />
                        })
                    }
                    {
                        films.length==0?<p className="m-tip null-film">暂无作品</p>: <p className="m-tip">没有更多了</p>
                    }
                </div>
                {
                    (user.isNotFollow == "3")?<Link to="/Login"><button className="join-us1 orange-btn remove-bg" onClick={this.toExit.bind(this)}>退出登录</button></Link>:<link></link>
                }
                {/*加关注弹框*/}
                <div className="model attention-model" ref="attention">
                    <div className="person-gz">
                        <img src={duihao} alt="图标" />
                        已关注
                    </div>
                </div>
                {/*取消关注*/}
                <div className="model cancel-model" ref="cancel_model">
                    <div className="person-qx">
                        <p className="p-1">取消关注</p>
                        <p className="p-2">确认要取消关注吗？</p>
                        <div className="buttons">
                            <button className="mob-btn" ref="cancel_attention" onClick={this.cancelAttention.bind(this)}>确认</button>
                            <button className="mob-btn quxiao" onClick={this.closeModel.bind(this)}>取消</button>
                        </div>
                    </div>
                </div>
            </div>
        )
    }
}

const MobileMine = connect(mapStateToProps,mapDispatchToProps)(MobileMineContainer) ;

export { MobileMine as default } ;